package cn.uyunsky.platform.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * @author baiyh
 * @date 2012-3-4
 */
public class ButtonTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;

	private static String STYLE_CLASS = "uyunsky_button";

	private String id = null;
	private String value = null;
	private String style = null;
    private String styleClass = null;

	public void setId(String id) {
		this.id = id;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setStyle(String style) {
		this.style = style;
	}

    public void setStyleClass(String styleClass) {
        this.styleClass = styleClass;
    }

    public void release() {
		super.release();
		id = null;
		value = null;
        style = null;
        styleClass = null;
	}

	public int doEndTag() throws JspException {
		return super.doEndTag();
	}

	public int doStartTag() throws JspException {
		write(this.pageContext, this.renderInputElement());
		return super.doStartTag();
	}

	protected String renderInputElement() throws JspException {
		StringBuffer results = new StringBuffer("<button");

		prepareAttribute(results, "id", id);
		prepareAttribute(results, "type", "button");

        if (!isEmpty(styleClass)) {
            prepareAttribute(results, "class", styleClass);
        }

		if (!isEmpty(style)) {
			prepareAttribute(results, "style", style);
		}
		prepareAttribute(results, "class", STYLE_CLASS);

		prepareOtherAttributes(results);

		results.append(this.getElementClose());
		results.append(value);
		results.append("</button>");
		return results.toString();
	}

	private String getElementClose() {
		return ">";
	}

	/**
	 * <p>
	 * </p>
	 * @param handlers
	 * @param name
	 * @param value
	 * void
	 */
	protected void prepareAttribute(StringBuffer handlers, String name, Object value) {
		if (value != null) {
			handlers.append(" ");
			handlers.append(name);
			handlers.append("=\"");
			handlers.append(value);
			handlers.append("\"");
		}
	}

	/**
	 * @param handlers
	 */
	protected void prepareOtherAttributes(StringBuffer handlers) {
	}

	private void write(PageContext pageContext, String text) throws JspException {
		JspWriter writer = pageContext.getOut();
		try {
			writer.print(text);
		} catch (IOException e) {
			throw new JspException("uyunsky tld error", e);
		}
	}

	protected boolean isEmpty(String val) {
		if (val == null || val.length() == 0)
			return true;
		else
			return false;
	}
}
